import crypto from 'crypto'
import jwt from 'jwt-simple'
import {
	tokenExp
} from '../../utils/constants.js'

import encryptPassword from '../../utils/encryptPassword.js';

import groupFunc from '../../utils/groupFunc.js';

const db = uniCloud.database();

async function Perform(event) {
	if (!event.name) {
		return {
			status: -4,
			msg: '请输入模板名称！'
		}
	}

	const collection = db.collection('ha_user_account');
	let user = await collection
		.doc(
			event.uid
		)
		.get();
	
	if (user.data && user.affectedDocs === 1){
	} else {
		return {
			status: -1,
			msg: "请重新登录！"
		}
	}

	const collection1 = db.collection('ha_group_list');
	let res1 = await collection1
		.doc(
			event.group_id
		)
		.get();
	
	if (res1.data && res1.affectedDocs === 1){
	} else {
		return {
			status: -2,
			msg: "请先进入团体，再创建！"
		}
	}

	const collection2 = db.collection('ha_template_list');
	let res2 = await collection2
		.doc(
			event.tpl_id
		)
		.get();
	
	if (res2.data && res2.affectedDocs === 1){
	} else {
		return {
			status: -3,
			msg: "抱歉，模板不存在！"
		}
	}

	let data = {
		group_id: event.group_id,
		group2_id: event.group_id,
		name: event.name,
		is_active: event.is_active,
		check_member: event.check_member,
		interval_hour: event.interval_hour,
		tpl_id: event.tpl_id,
		tpl_name: res2.data[0].name,
		content: res2.data[0].content
	}

	const collection3 = db.collection('ha_report_list');
	let res3 = await collection3.add(data);

	// 创建下属团体的报备记录
	let childList = await groupFunc.getChildGroupID(event.group_id,0);

	for ( let i = 0; i < childList.length; i++ ) {
		data.group_id = childList[i];
		await db.collection('ha_report_list').add(data);
	}

	return {
		status: 0,
		report_id: res3.id,
		child: childList, // 调试查看子团体
		msg: "创建成功！"
	}
}

export {
	Perform as main
}
